/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 */
package edu.harvard.s3xyback;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;


/**
 * Config Controller.
 */
public class ConfigController implements Initializable {

    @FXML
    Button browse;
    @FXML
    Label errorMessage;
    @FXML
    ListView directory;
    @FXML
    PasswordField password;
    @FXML
    PasswordField accesskey;
    @FXML
    PasswordField secretkey;
    @FXML
    TextField email;
    @FXML
    TextField bucketName;
    @FXML
    ChoiceBox checkdays;
    @FXML
    ChoiceBox report;
    @FXML
    CheckBox autorestore;
    @FXML
    Button save;
    @FXML
    Button delete;
    

    
    private ObservableList data = FXCollections.observableArrayList();
    private Main application;
   
    public void setApp(Main application){
        this.application = application;
    }

    @Override
    public void initialize(URL url, ResourceBundle rsrcs) {
        assert browse != null : "fx:id=\"browse\" was not injected: check your FXML file 'Config.fxml'.";
        assert errorMessage != null : "fx:id=\"errorMessage\" was not injected: check your FXML file 'Config.fxml'.";
        assert directory != null : "fx:id=\"directory\" was not injected: check your FXML file 'Config.fxml'.";
        assert password != null : "fx:id=\"password\" was not injected: check your FXML file 'Config.fxml'.";
        assert accesskey != null : "fx:id=\"accesskey\" was not injected: check your FXML file 'Config.fxml'.";
        assert secretkey != null : "fx:id=\"secretkey\" was not injected: check your FXML file 'Config.fxml'.";
        assert email != null : "fx:id=\"email\" was not injected: check your FXML file 'Config.fxml'.";
        assert checkdays != null : "fx:id=\"checkdays\" was not injected: check your FXML file 'Config.fxml'.";
        assert report != null : "fx:id=\"report\" was not injected: check your FXML file 'Config.fxml'.";
        assert autorestore != null : "fx:id=\"autorestore\" was not injected: check your FXML file 'Config.fxml'.";
        assert save != null : "fx:id=\"save\" was not injected: check your FXML file 'Config.fxml'.";
        assert delete != null : "fx:id=\"delete\" was not injected: check your FXML file 'Config.fxml'.";
        assert bucketName != null : "fx:id=\"bucketName\" was not injected: check your FXML file 'Config.fxml'.";
        
        errorMessage.setText("");
        checkdays.setTooltip(new Tooltip("How often files are checked for corruption"));
        report.setTooltip(new Tooltip("How often email reports are generated"));
        accesskey.setTooltip(new Tooltip("See http://aws.amazon.com/security-credentials"));
        secretkey.setTooltip(new Tooltip("See http://aws.amazon.com/security-credentials"));
        email.setTooltip(new Tooltip("Please enter a valid email address"));
        bucketName.setTooltip(new Tooltip("e.g. 'my_bucket'; a random string will be appended automatically"));
        report.setItems(FXCollections.observableArrayList("DAILY", "WEEKLY", "MONTHLY"));
        checkdays.setItems(FXCollections.observableArrayList("1", "2", "3", "4", "5"));
        
        if (new File("my_properties.properties").exists()) {
            try {
                Properties configFile = new Properties();
                configFile.load(ConfigController.class.getResourceAsStream("my_properties.properties"));
                accesskey.setText(configFile.getProperty("accessKey"));
                secretkey.setText(configFile.getProperty("secretKey"));
                email.setText(configFile.getProperty("email"));
                checkdays.setValue(configFile.getProperty("checkDays"));
                report.setValue(configFile.getProperty("reportSched"));
                password.setDisable(true);
                bucketName.setDisable(true);
                autorestore.setSelected(Boolean.valueOf(configFile.getProperty("autorestore")));
                String[] dirs = configFile.getProperty("directories").split(",");
                ObservableList o = FXCollections.observableArrayList();
                for (String s : dirs) {
                    o.add(s); 
                }
                directory.setItems(o);
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    @FXML
    public void browse(ActionEvent event) throws IOException {
        if (application == null){
            // We are running in isolated FXML, possibly in Scene Builder.
            // NO-OP.
            System.out.println("Application==NULL");
            errorMessage.setText("Application==NULL");
        } else {
            DirectoryChooser fileSelector = new DirectoryChooser();
            fileSelector.setTitle("Select Root Directory");
            File f = fileSelector.showDialog(application.getStage());
            if (f != null && !data.contains(f.getAbsolutePath())) {
                if (isSubDirectoryOfAny(data, f)) {
                    errorMessage.setText("A parent directory for " + f + " has already been specified");
                }
                else {
                    data.add(f.getAbsolutePath());
                    directory.setItems(data);
                }
            }
        }
    }
    
    @FXML
    private void deleteAction(ActionEvent event){
        int selectedItem = directory.getSelectionModel().getSelectedIndex();
        if (selectedItem != -1) {
            data.remove(selectedItem);
        }
    }
    
    @FXML
    public void save(ActionEvent event) {
        application.gotoFXML();
//        String[] dir = new String[data.size()];
//        int i = 0;
//        for (Object s : data) {
//            dir[i] = (String)(s);
//            i++;
//        }
//
//        //String dir = directory.getText();
//        String pass = password.getText().trim();
//        String access = accesskey.getText().trim();
//        String secret = secretkey.getText().trim();
//        String mail = email.getText().trim();
//        String bucket = bucketName.getText().trim();
//        String sched = (String)report.getValue();
//        String check = (String)checkdays.getValue();
//        String restore = "false";
//        if (autorestore.isSelected());
//            restore = "true";
//        if (dir==null || pass=="" || access=="" || secret=="" || bucket=="" || sched==null || check==null) {
//            errorMessage.setText("Please fill all required fields");
//        }
//        else {
//            boolean flag = true;
//            for (String d : dir) {
//                if (!new File(d).exists()) {
//                    errorMessage.setText("Please specify a valid directory " + d);
//                    flag = false;
//                }
//            }
//            if (flag) {
//                ConfigClient setUp = new ConfigClient("my_properties.properties");
//
//                // causes the JavaFX application to terminate
//                //Platform.exit();
//                
//                // creates configuration file with indicated values
//                setUp.createConfigFile(access, secret, mail, bucket, check, sched, restore, dir);
//                
//                // uses the password provided to generate a key/salt pair
//                File keyFile = new File("aws_key");
//                if (keyFile.exists()) {
//                    System.out.println("Changing key/salt files not currently supported");
//                }
//                else {
//                    AESKeyFactory.generateKey(pass, "aws_key", "aws_salt");
//                }
//                application.gotoFXML();
//            }
//        }
    }
    public static boolean isSubDirectory(File base, File child)
      throws IOException {
      base = base.getCanonicalFile();
      child = child.getCanonicalFile();

      File parentFile = child;
      while (parentFile != null) {
          if (base.equals(parentFile)) {
              return true;
          }
          parentFile = parentFile.getParentFile();
      }
      return false;
  }
    public static boolean isSubDirectoryOfAny(ObservableList base, File child)
        throws IOException {
        ArrayList<String>dirs = new ArrayList<String>();
        for (Object s : base) {
            dirs.add((String)(s));
        }
        for (String s : dirs) {
            if (isSubDirectory(new File(s), child))
                return true;
        }
        return false;
    }
}